import asyncio
import logging

from sqlalchemy.ext.asyncio import AsyncSession

from src.application.bot_settings.service import BotSettingsService
from src.application.proxy.service import ProxyService
from src.presentation.tg_bot.worker.jobs.check_proxy import check_proxy

logger = logging.getLogger(__name__)


async def proxy_checker(ctx) -> None:
    """
    Checking all proxies in shop
    Marking invalid proxies
    """
    session: AsyncSession = ctx["session"]
    proxy_service: ProxyService = ctx["proxy_service"]
    bot_settings_service: BotSettingsService = ctx["bot_settings_service"]

    bot_settings = await bot_settings_service.get_bot_settings()
    if bot_settings and bot_settings.proxy_checker_status:
        logger.info("Начинаю проверку всех прокси")
        proxies = await proxy_service.get_all_proxies()

        if len(proxies.proxies) > 0:
            sem = asyncio.Semaphore(6)
            # TODO Кидать задачу в редис а не вызывать через функцию
            # TODO Добавить получение сервера прокси
            tasks = [
                asyncio.ensure_future(check_proxy(ctx, sem=sem, proxy=proxy, session=session))
                for proxy in proxies.proxies
            ]
            await asyncio.gather(*tasks)
            logger.info(f"Проверил {len(all_proxies)} прокси")
